SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[wp_List_Generic]
 @Table VARCHAR(MAX),
 @DefaultSort VARCHAR(MAX),

 @Start INT = 0,  
 @Limit INT = 25,  
 @Order VARCHAR(MAX) = 'descripcion',  
 @Direction VARCHAR(4) = 'ASC',  
   
 @Filtro VARCHAR(MAX) = NULL  
AS  
  
DECLARE @SQL NVARCHAR(MAX),  
  @ParmDefinition NVARCHAR(MAX) = N'@Start INT,  
 @Limit INT'  
  
SET @SQL = '  
WITH TableRowNumber AS (  
    Select ROW_NUMBER() OVER (Order by '+ISNULL(@Order, @DefaultSort)+ ' ' + ISNULL(@Direction, 'ASC') +') as RNumber, *   
 from ' + @Table 
IF(NOT @Filtro IS NULL AND @Filtro <> '')  
BEGIN   
	SET @SQL = @SQL + ' Where ' + @Filtro  
END  
SET @SQL = @SQL + ')  

SELECT *  
FROM TableRowNumber'

IF(@Limit > 0)
BEGIN
	SET @SQL = @SQL + '
		Where RNumber between @Start + 1 and @Start + @Limit   
		 '  
		 
	IF(NOT @Filtro IS NULL AND @Filtro <> '')  
	BEGIN   
	 SET @SQL = @SQL + ' AND ' + @Filtro  
	END  
END
ELSE
BEGIN
	IF(NOT @Filtro IS NULL AND @Filtro <> '')  
	BEGIN   
	 SET @SQL = @SQL + ' Where ' + @Filtro  
	END  
END 

SET @SQL = @SQL + '  
Select Count(1)  
From ' + @Table

IF(NOT @Filtro IS NULL AND @Filtro <> '')  
BEGIN   
 SET @SQL = @SQL + ' WHERE ' + @Filtro  
END  
  
  
PRINT @SQL  
EXECUTE sp_executesql @SQL,   
 @ParmDefinition,  
 @Start = @Start,  
 @Limit = @Limit
GO
